
import BaseAds from "./BaseAds";
import { EventTool } from "../Tool/EventTool";
import KongFuLoader from "../../MyLoader/KongFuResourLoader";
import MathTool from "../Tool/MathTool";
import MsgDispatcher, { MsgType } from "../Tool/MsgDispatcher";
import GameManager from "../Manager/GameManager";
import { BannerAdConfig, VedioAdConfig } from "../../MyLoader/KongLoaderData";
import UIManager from "../UI/UIManager";
import WaitingView from "../../View/WaittingView";
import { TipView } from "../../View/TipView";
import GameAdsManager from "./GameAdsManager";
import SoundMgr from "../Manager/SoundMgr";

class BannerData {
    public Banner: any = null;
    public BannerId: string = "";
    public BannerType: string = "";
    public StartLevel: string = "";
    public Desc: string = "";
    public IsShow:boolean=false;
}


class VedioData {
    public Video:any = null;
    public VideoId: string = "";
    public VideoType: string = "";
    public Desc: string = "";
    public VideoLoaded: boolean = false;
}

    export class WeChatAd extends BaseAds {

    //bannner
    private s_RewardBannerId = "PBgAAQCqkzN9e3go";

    //InterstitialAd
    private s_InterstitialAdId = "adunit-0e410977ddf22f99";
    //gridAd
    private s_gtridAdId = "adunit-eee7b8e7979ce325";

       //video
    private  s_RewardVideoAd:RewardedVideoAd=null;
    private  s_rewardVideoLoaded=false;

    private m_banners: { [key: string]: BannerData } = {};
    private m_videos: { [key: string]: VedioData } = {};

    //interstitial
    private s_interstitialLoaded = false;
    private s_InterstitialAd: InterstitialAd = null;
    //GameIcon
    private s_GameIconInterstitialLoaded = false;
    private s_GameIcon: GameIcon = null;
    //gridAd
    private s_gridAd: any = null;

    private s_safeHeight = 0;
    private m_currentVideoType:string="";

    ///是否有激励视频广告
    public  get HasRewardVideo()
    {
        console.log("HasRewardVideo");

        if (this.s_RewardVideoAd==null) 
        {
            this.Created30RewardedVideoAd();
            return false;
        }
        //未加载
        if (!this.s_rewardVideoLoaded) {
            this.s_RewardVideoAd.load();
        }
        return this.s_rewardVideoLoaded;
    }


    OnShow(callBack: Function)  {
        this.m_platform.onShow(callBack);
    }

    ///是否有插屏广告
    public get HasInterstiatialAd()  {

        if (this.s_InterstitialAd == null) {
            this.CreatedInterstitialAd();
            return false;
        }
        //未加载
        if (!this.s_interstitialLoaded && this.CanShowInterstitialAd()) {
            this.s_InterstitialAd.load();
        }
        return this.s_interstitialLoaded;
    }

    public get SyncSystemInfo()  {
        if (this.s_syncsystemInfoS == null) {
            this.s_syncsystemInfoS = this.m_platform.getSystemInfoSync();
            this.SDKVersion = this.s_syncsystemInfoS.SDKVersion;
            console.log("model=" + this.s_syncsystemInfoS.model);
            console.log("pixelRatio=" + this.s_syncsystemInfoS.pixelRatio);
            console.log("windowWidth=" + this.s_syncsystemInfoS.windowWidth);
            console.log("windowHeight=" + this.s_syncsystemInfoS.windowHeight);
            console.log("ScreenWidth=" + this.s_syncsystemInfoS.screenWidth);
            console.log("screenHeight=" + this.s_syncsystemInfoS.screenHeight);
            console.log(this.s_syncsystemInfoS.language);
            console.log(this.s_syncsystemInfoS.version);
            console.log(this.s_syncsystemInfoS.SDKVersion);
            console.log(this.s_syncsystemInfoS.platform);
        }
        return this.s_syncsystemInfoS;
    }

    //SDK版本
    private SDKVersion = "0.0.0";

    public InitAd(ishowbannerfc: Function = null, ishowintersitialfc: Function = null)  {
        this.s_IsShowIntersitialmetd = ishowintersitialfc;
        this.s_IsShowIntersitialmetd = ishowbannerfc;
        MsgDispatcher.Register(MsgType.AssetsLoadOver, "WeChatAd", this.StartLoadBanner.bind(this));
        MsgDispatcher.Register(MsgType.GameLoadOver, "WeChatAd", this.OnGameLoadOver.bind(this));
        this.HasInterstiatialAd;
        wx.showShareMenu({ success: () => { }, fail: () => { }, complete: () => { }, withShareTicket: true });
        Laya.timer.frameLoop(20,this,this.UpdateBannerState)
    }

    StartLoadBanner(){
        Laya.loader.create( KongFuLoader.Instance.s_bannerConfigPath, Laya.Handler.create(this, this.InitBanner));
    }

    OnGameLoadOver() 
    {
        // this.InitBanner();
        GameAdsManager.Instance.ShowBannerAd("SettingBanner");
        this.HasRewardVideo;
        let matrixconfigdata=KongFuLoader.Instance.GetMatrixAdConfig;
        GameAdsManager.Instance.SetUseShare(matrixconfigdata.useshare);
        wx.onShareAppMessage(() => {
            let wechatShareInfo = KongFuLoader.Instance.GetWxShareData();
            if (wechatShareInfo.length < 1) return;
            let index = MathTool.GetRandomInt(0, wechatShareInfo.length);
            wx.shareAppMessage(
                {
                    title: wechatShareInfo[index].Title,
                    imageUrl: wechatShareInfo[index].ImageUrl,
                })
        });
        // Laya.stage.on(Laya.Event.CLICK, this, this.Subscribesject);
    }



    //显示GameIcon
    public ShowGameIcon()  {
        if (!this.CanShowCreateGameIcon()) {
            return;
        }
        if (this.SyncSystemInfo == null) {
            console.log("未获取到系统信息 游戏图标显示失败");
            return;
        }

        console.log("WeChatAd.s_GameIconInterstitialLoaded=" + this.s_GameIconInterstitialLoaded);
        if (this.s_GameIconInterstitialLoaded && this.s_GameIcon != null)  {
            console.log("this.gameIconSHow");
            this.s_GameIcon.show();
        }
    }

    //隐藏游戏Icon
    public HideGameIcon()  {
        if (this.s_GameIcon != null) {
            this.s_GameIcon.hide();
        }
    }

    //隐藏游戏Icon并创建新的game Icon
    public HideGameIconAndCreateNew()  {
        if (this.s_GameIcon != null) {
            this.s_GameIcon.hide();
            this.s_GameIcon.load()
        }
    }


    InitBanner(){
        let bannerdata = KongFuLoader.Instance.GetBannerConfigData();
        for (let index = 0; index < bannerdata.length; index++) {
            const element: BannerAdConfig = bannerdata[index];
            let bannerAd = this.m_platform.createBannerAd({
                adUnitId: element.BannerId,
                adIntervals: 30,
                style: {
                    width: 300,
                    left: (this.SyncSystemInfo.screenWidth - 300) / 2 + 0.1,
                    top: this.SyncSystemInfo.screenHeight - 105,
                }
            })

            bannerAd.onLoad(() => {
                let newbannerdata = new BannerData();
                newbannerdata.Banner = bannerAd;
                newbannerdata.BannerId = element.BannerId;
                newbannerdata.BannerType = element.BannerType;
                newbannerdata.StartLevel = element.StartLevel;
                newbannerdata.Desc = element.Desc;
                this.m_banners[element.BannerType] = newbannerdata;
                console.log(element.BannerType + ' banner 广告加载成功')
            })

            bannerAd.onResize(size =>  {
                console.log("bannerSize=" + size.width + " height=" + size.height + " realwidth=" + bannerAd.style.realWidth + " realheight=" + bannerAd.style.realHeight);
                bannerAd.style.left = (this.SyncSystemInfo.screenWidth - size.width) / 2 + 0.1;
                bannerAd.style.top = this.SyncSystemInfo.screenHeight - size.height + 0.1;
            }
            );

            bannerAd.onError(err => {
                console.error("BannerIdError" + err);
                EventTool.LogEvent("banner加载失败 " + err);
            })
        }
    

    }



   
    ////////////RewardVidoe=============================
    private  Created30RewardedVideoAd()
    {
        if (!this.CanShowRewardVideoAd()) 
        {
            return;
        }
        let videodata = KongFuLoader.Instance.GetVideoConfigData();
        this.s_RewardVideoAd = this.m_platform.createRewardedVideoAd({ adUnitId: videodata[0].VideoId })
        this.s_RewardVideoAd.onLoad(() => {
            this.s_rewardVideoLoaded=true;
            EventTool.LogEvent("激励视频30秒加载成功");
            console.log('激励视频 广告加载成功')
          })
          this.s_RewardVideoAd.onError(err => {
            this.s_rewardVideoLoaded=false;
            this.Created15RewardedVideoAd();
            EventTool.LogEvent("激励视频30秒加载失败 "+err);
            console.log("30激励加载失败:"+err)
          })

          this.s_RewardVideoAd.onClose(res=>
          {
            SoundMgr.instance.ReSumeBgm();
            EventTool.LogEvent("激励视频退出观看");
              if (this.s_videoCallBack!=null) {
                if (res && res.isEnded || res === undefined) 
                {
                    // 正常播放结束，可以下发游戏奖励
                    this.s_videoCallBack(true);
                }
                  else{
                    this.s_videoCallBack(false);
                  }
                  this.s_videoCallBack=null;
              }
               UIManager.Instance.HideInterView(WaitingView.name);
          });  
    }


    private  Created15RewardedVideoAd()
    {
        let videodata = KongFuLoader.Instance.GetVideoConfigData();
        let videoId=videodata[0].VideoId
        if (videodata.length>1)videoId=videodata[1].VideoId;
        this.s_RewardVideoAd= this.m_platform.createRewardedVideoAd({ adUnitId: videodata[1].VideoId })
        this.s_RewardVideoAd.onLoad(() => {
          //  this.s_rewardVideoLoaded=true;
          EventTool.LogEvent("激励视频15秒加载成功");
            console.log('15激励视频 广告加载成功')
          })
          this.s_RewardVideoAd.onError(err => {
           // this.s_rewardVideoLoaded=false;
           EventTool.LogEvent("激励视频15秒加载失败 "+err);
            console.log("15激励加载失败:"+err)
          })
    }

    //显示广告
    public ShowBannerAd(bannerType: string)  {
        if (this.m_banners[bannerType] != null) {
            console.log(GameManager.GetInstance().CurrentLevelId + " " + this.m_banners[bannerType].StartLevel);
            if (GameManager.GetInstance().CurrentLevelId < this.m_banners[bannerType].StartLevel) {
                return;
            }
            this.m_banners[bannerType].IsShow=true;
            this.m_banners[bannerType].Banner.show();
        }
    }

    //隐藏Banner广告
    public HideBannerAd(bannerType: string)  {
        if (this.m_banners[bannerType] != null) {
            this.m_banners[bannerType].Banner.hide();
        }
    }


    //=============显示格子广告=====================
    public ShowGridAd()  {
        if (this.s_gridAd != null) this.s_gridAd.show();
    }

    public HideGirdAd()  {
        if (this.s_gridAd != null) this.s_gridAd.hide();
    }


     //显示激励视频广告
     public  ShowRewardVieoAd(callback:Function)
     {  
        UIManager.Instance.ShowInterView(WaitingView.name);
        this.s_videoCallBack=callback;
        if (this.HasRewardVideo) 
        {
            this.s_RewardVideoAd.show().
            then(()=>
            {
                this.s_rewardVideoLoaded=false
            }
            ).
            catch(e=>
            {
                this.s_interstitialLoaded=false
                console.error(e.message);
                this.s_videoCallBack(false);
                UIManager.Instance.ShowInterView(TipView.name,"奖励正在准备中，请稍后再试");
                UIManager.Instance.HideInterView(WaitingView.name);
            }); 
        }
        else{ 
            this.s_videoCallBack=null;
             UIManager.Instance.ShowInterView(TipView.name,"奖励正在准备中，请稍后再试");
            UIManager.Instance.HideInterView(WaitingView.name);
        }
           
     }
    
     
    //显示插屏广告
    public ShowInterstitialAd(callback = null, type?: number)  {
        if (this.s_IsShowIntersitialmetd != null && !this.s_IsShowIntersitialmetd()) {
            return;
        }
        this.s_interstitialAdCallBack = callback;
        if (this.HasInterstiatialAd) {
            this.s_InterstitialAd.show().
                then( ()=>{
                    EventTool.LogEvent("插屏成功展示");
                    this.s_interstitialLoaded = false
                }
                ).
                catch(function (e)  {
                    this.s_interstitialLoaded = false
                    EventTool.LogEvent("插屏加载失败 " + e.message);
                    console.error(e.message);
                });
        }
    }



    public CanShowBannerAd()  {
        if (this.SDKVersion == "0.0.0")  {
            this.SyncSystemInfo;
        }
        return this.compareVersion(this.SDKVersion, '2.0.4') >= 0;
    }

    public CanShowRewardVideoAd()  {
        if (this.SDKVersion == "0.0.0")  {
            this.SyncSystemInfo;
        }
        return this.compareVersion(this.SDKVersion, '2.0.4') >= 0;
    }

    public CanShowInterstitialAd()  {
        if (this.SDKVersion == "0.0.0")  {
            this.SyncSystemInfo;
        }
        return this.compareVersion(this.SDKVersion, '2.6.0') >= 0;
    }

    public CanShowRank()  {
        if (this.SDKVersion == "0.0.0")  {
            this.SyncSystemInfo;
        }
        return this.compareVersion(this.SDKVersion, "1.9.92") >= 0;
    }

    public CanShowCreateGameIcon()  {
        if (this.SDKVersion == "0.0.0")  {
            this.SyncSystemInfo;
        }
        return this.compareVersion(this.SDKVersion, "2.8.3") >= 0;
    }


    public CanGetMenueButtonOrLoadSubPackage()  {
        if (this.SDKVersion == "0.0.0")  {
            this.SyncSystemInfo;
        }
        return this.compareVersion(this.SDKVersion, "2.1.0") >= 0;
    }

    public CanShowGrid()  {
        if (this.SDKVersion == "0.0.0")  {
            this.SyncSystemInfo;
        }
        return this.compareVersion(this.SDKVersion, "2.9.2") >= 0;
    }


    ///////////////============================================插屏广告=============

    private CreatedInterstitialAd()  {
        if (!this.CanShowInterstitialAd()) {
            return;
        }
        this.s_InterstitialAd = this.m_platform.createInterstitialAd({ adUnitId: this.s_InterstitialAdId })
        this.s_InterstitialAd.onLoad(() => {
            this.s_interstitialLoaded = true;
            console.log('插屏 广告加载成功')
        })
        this.s_InterstitialAd.onError(err => {
            this.s_interstitialLoaded = false;
            console.log("插屏广告加载失败:" + err)
        })

        this.s_InterstitialAd.onClose(e =>  {
            if (this.s_interstitialAdCallBack != null)  {
                this.s_interstitialAdCallBack();
            }

            this.s_interstitialAdCallBack = null;
        })
    }

    //======================================格子广告==========================================
    public CreateGridAd()  {
        if (!this.CanShowGrid()) return;
        this.s_gridAd = this.m_platform.createGridAd({
            adUnitId: this.s_gtridAdId,
            adIntervals: 30, // 自动刷新频率不能小于30秒
            style: {
                width: 300,
                left: (this.SyncSystemInfo.screenWidth - 300) / 2 + 0.1,
                top: this.SyncSystemInfo.screenHeight - 105,
            }
            // ...
        })
        this.s_gridAd.onError(err => {
            console.log("格子广告加载失败 " + err)
        })
        this.s_gridAd.onLoad(err => {
            console.log("格子广告加载成功 ")
        })

        this.s_gridAd.onResize(res => {
            this.s_gridAd.style.left = (this.SyncSystemInfo.screenWidth - res.width) / 2 + 0.1;
            this.s_gridAd.style.top = this.SyncSystemInfo.screenHeight - res.height + 0.1;
        })
    }

    ///=======================游戏Icon==========

    public CreateGameIcon()  {
        if (!this.CanShowCreateGameIcon()) {
            return;
        }
        console.log("CreateGameIcon=======");
        // 在适合的场景显示推荐位 if (iconAd) {  iconAd.load().then(() => {    iconAd.show()  }).catch((err) => {    console.error(err)  }) }
        this.s_GameIconInterstitialLoaded = false;
        let iconAd = this.m_platform.createGameIcon(
            {
                adUnitId: this.s_RewardBannerId,
                count: 2,
                style: [],
            },
            {
            }
        );

        iconAd.onLoad(() => {

            console.log('CreateGameIcon 广告加载成功')
            this.s_GameIcon = iconAd;
            this.s_GameIconInterstitialLoaded = true;
        })
        iconAd.onResize(size =>  {
            iconAd.icons[0].size = 40;
            iconAd.icons[1].size = 40;
            iconAd.icons[0].color = "white"
            iconAd.icons[1].color = "white"
            let top1 = 60;
            let top2 = 120;
            let top3 = 90;
            let top4 = 180;
            if (this.SyncSystemInfo.screenHeight / this.SyncSystemInfo.screenWidth < 2) {
                iconAd.icons[0].top = top1;
                iconAd.icons[1].top = top1;
            }
            else {
                iconAd.icons[0].top = top3;
                iconAd.icons[1].top = top3;
            }
            iconAd.icons[0].left = 0;
            iconAd.icons[1].left = this.SyncSystemInfo.screenWidth - 70;

        }
        );

        iconAd.onError(err => {
            this.s_GameIconInterstitialLoaded = false;
            console.error("CreateGameIcon " + err.errMsg + " code=" + err.errCode);
        })

    }

    public CreateNewGameIcon() {

        if (this.s_GameIcon != null)  {
            this.s_GameIcon.destroy();
            this.s_GameIcon = null;
        }

        this.s_GameIconInterstitialLoaded = false;
        this.CreateGameIcon();
    }


    //版本号比较
    public compareVersion(v1, v2) {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)

        while (v1.length < len) {
            v1.push('0')
        }
        while (v2.length < len) {
            v2.push('0')
        }

        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])

            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }
        return 0
    }


    //
    public NativeToProgram(gameId: string,gameName:string, gamepath: string,adtype:string,order:number)  {

        this.m_platform.navigateToMiniProgram({
            appId: gameId,
            path: gamepath,
            extraData: {
                foo: 'bar'
            },
            envVersion: 'release',
            success(res) {
                console.log("navigateToMiniProgram success ");
                EventTool.UpLoadUserAdData(adtype,order,gameId,"3");
                // 打开成功
            },
            fail()  {
                console.log("navigateToMiniProgram fail ");
                EventTool.UpLoadUserAdData(adtype,order,gameId,"4");
            },
            complete() {},
        })
    }


    OnAudioInterruptionEnd(callBack: Function)  {
        if (this.compareVersion(this.SDKVersion, "2.1.0") >= 0) {
            this.m_platform.onAudioInterruptionEnd(callBack);
        }
    }



    UpdateBannerState(){
        for (var key in this.m_banners) 
        {
           if (!this.m_banners[key].IsShow){
                this.m_banners[key].Banner&&this.m_banners[key].Banner.hide();
           }
        }
    }
}